package com.leo.base_project.activity.module_Impl.bluImpl;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.Nullable;

import com.leo.base_project.Utils.LogUtils;
import com.leo.base_project.Utils.UIUtils;
import com.leo.base_project.activity.base.BaseActivityX;
import com.leo.base_project.databinding.ActivityBluBinding;
import com.leo.base_project.entity.BluDevice;
import com.leo.base_project.entity.BluDeviceDao;
import com.leo.base_project.module.blu.BTUtils;
import com.leo.base_project.module.blu.BluetoothChatService;

import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.List;

import static com.leo.base_project.Utils.UIUtils.toast;
import static com.leo.base_project.module.blu.BTUtils.MESSAGE_READ;
import static com.leo.base_project.module.blu.BTUtils.MESSAGE_STATE_CHANGE;

/*
 * 类名：BluActivity
 * 功能：蓝牙功能的具体实现类，主要功能都写在里头了
 * 创建时间: 2021/8/25 16:06
 * 创建者：Leo
 */
@SuppressLint("NonConstantResourceId")
public class BluTestActivity extends BaseActivityX {

    //-----------------------组件-----------------------

    ActivityBluBinding binding;

    // ---------------用于通信的 Handler-----------------
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothChatService mChatService;
    private BluDevice blu_device;
    BluDeviceDao bluDeviceDao;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBluBinding.inflate(getLayoutInflater());
        View root = binding.getRoot();
        setContentView(root);
        bluDeviceDao = daoSession.getBluDeviceDao();
        initButton();
        initBlueTooth();
    }

    private void initButton() {
        // 连接设备
        binding.btnBluConnectDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (blu_device != null){
                    setupChat();
                }else {
                    UIUtils.toast("连接设备不能为空");
                }
            }
        });

        binding.btnBluDisconnectDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                disconnectDevice();
            }
        });

        binding.btnBluSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!binding.tvBluConnectState.getText().toString().equals("连接成功")){
                    UIUtils.toast("设备未连接");
                    return;
                }
                String s = binding.edBluSendData.getText().toString();
                if (!StringUtils.isBlank(s)){
                    byte[] send = s.getBytes();
                    mChatService.write(send);
                    binding.edBluSendData.setText("");
                }
            }
        });
    }

    /*
     * 功能：蓝牙初始化，测试是否能打开蓝牙，无法打开则直接退出当前界面
     * 创建时间: 2021/8/25 15:46
     * 创建者：Leo
     */
    private void initBlueTooth() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            UIUtils.toast("无法打开蓝牙");
        }
        // 初始化连接
        setupChat();
    }

    /*
     * 功能：建立蓝牙连接，通过DeviceActivity发回来的数据
     * 创建时间: 2021/8/25 15:49
     * 创建者：Leo
     */
    private void setupChat() {
        if (blu_device != null) {
            if (mChatService != null) {
                mChatService.stop();
            }
            mChatService = new BluetoothChatService(this, mHandler);
            // 1.获得蓝牙设备对象
            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(blu_device.getDevice_address());
            // 2.连接
            mChatService.connect(device);
        }
    }

    /*
     * 功能：通过与BluetoothChatService的绑定，蓝牙状态变化时开始变化
     * 创建时间: 2021/8/25 15:53
     * 创建者：Leo
     */
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothChatService.STATE_CONNECTED:
                            // 连接成功的状态
                            toast("连接成功...");
                            updateState("连接成功");
                            // 把当前的设备存到数据库里
                            saveDevice(true);
                            break;
                        case BluetoothChatService.STATE_CONNECTING:
                            toast("连接中...");
                            updateState("连接中");
                            // 正在连接的状态
                            break;
                        case BluetoothChatService.STATE_NONE:
                            // 无连接状态
                            toast("无连接...");
                            updateState("无连接");
                            break;
                    }
                    break;
                //------------------------------------从设备获取数据---------------------------------
                case MESSAGE_READ:
                    //添加到buffer
//                    readBuf.add()byte[]) msg.obj;
                    // 收到一次信息，转换为byte数组
                    binding.edBluReceiveData.setText("");
                    byte[] obj = (byte[]) msg.obj;
                    binding.edBluReceiveData.setText(new String(obj));
                    // 对收到的消息进行一定的处理
                    break;
            }
        }
    };

    /*
     * 功能：把成功连接的设备存起来
     * 输入：上线还是下线
     * 创建时间: 2021/8/26 14:10
     * 创建者：Leo
     */
    private void saveDevice(boolean isOnline) {
        if (blu_device == null) {
            UIUtils.toast("未找到需要保存的设备");
            return;
        }
        List<BluDevice> queryBluDevices = bluDeviceDao.loadAll();
        for (BluDevice device : queryBluDevices) {
            // 如果存在相同的 mac地址需要覆盖
            if (device.getDevice_address().equals(blu_device.getDevice_address())) {
                blu_device.setId(device.getId());
            }
        }
        if (isOnline) {
            blu_device.setOnlineTime(new Date());
        } else {
            blu_device.setOfflineTime(new Date());
        }
        bluDeviceDao.save(blu_device);
    }

    /*
     * 功能：打开设备检索列表，获取回调方法
     * 创建时间: 2021/8/25 15:56
     * 创建者：Leo
     */
    private void scanDevice() {
        disconnectDevice();
        Intent intent = new Intent(this, DeviceScanActivity.class);
        startActivityForResult(intent, BTUtils.SCAN_DEVICE);
    }

    /*
     * 功能：停止连接池，中断所有连接
     * 创建时间: 2021/8/26 14:15
     * 创建者：Leo
     */
    private void disconnectDevice() {
        try {
            if (mChatService != null) {
                mChatService.stop();
            }
        } catch (Exception e) {
            LogUtils.v(e.getLocalizedMessage());
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 返回一个蓝牙设备
        if (requestCode == BTUtils.SCAN_DEVICE && resultCode == BTUtils.SUCCESS) {
            blu_device = new BluDevice();
            if (data != null) {
                String device_name = data.getStringExtra(BTUtils.EXTRAS_DEVICE_NAME);
                blu_device.setDevice_name(device_name);
                blu_device.setDevice_address(data.getStringExtra(BTUtils.EXTRAS_DEVICE_ADDRESS));
                updateState(device_name);
            } else {
                toast("返回数据为空");
            }
        }
    }

    private void updateState(String state) {
        binding.tvBluConnectState.setText(state);
    }

    public void scan(View view) {
        scanDevice();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disconnectDevice();
        saveDevice(false);
    }
}